package com.zijidelu.luframework.starter.translate;

import com.zijidelu.luframework.api.model.ApiRequest;
import com.zijidelu.luframework.api.model.ApiResult;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 翻译切面。
 *
 * @author ZIJIDELU
 * @datetime 2025/10/15 22:38
 */
@Aspect
@Component
@RequiredArgsConstructor
public class DictTranslateAspect {
    /**
     * 定义切入点前置
     */
    @Pointcut("@annotation(com.zijidelu.luframework.base.dict.DictTranslateBefore)")
    public void translateBeforePointcut() {
    }

    /**
     * 定义切入点后置
     */
    @Pointcut("@annotation(com.zijidelu.luframework.base.dict.DictTranslateAfter)")
    public void translateAfterPointcut() {
    }

    @Before("translateBeforePointcut()")
    public void translateBefore(JoinPoint joinPoint) {
        Object[] paramValues = joinPoint.getArgs();
        for (Object paramValue : paramValues) {
            if (paramValue instanceof ApiRequest<?> apiRequest) {
                DictTranslateUtil.translateObject(apiRequest.getPayload());
                continue;
            }

            DictTranslateUtil.translateObject(paramValue);
        }
    }

    @AfterReturning(
            pointcut = "translateAfterPointcut()",
            returning = "result"
    )
    public void translateAfter(Object result) {
        if (result instanceof ApiResult<?> apiResult) {
            DictTranslateUtil.translateObject(apiResult.getPayload());
        } else {
            DictTranslateUtil.translateObject(result);
        }
    }
}
